package com.pdg.mcplugin.common.deprecated;

import java.util.HashMap;
import java.util.Map;

import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;

import com.pdg.mcplugin.common.baseclasses.PluginBase;
import com.pdg.mcplugin.common.baseclasses.PluginClientBase;

public abstract class DeprecatedPermissionCheckerBase<E extends PluginBase> extends PluginClientBase<E> implements DeprecatedPermissionChecker{

	public DeprecatedPermissionCheckerBase(E thePlugin) {
		super(thePlugin);
	}
	private Map<String,Boolean> defaults = new HashMap<String,Boolean>();
	
	protected void setDefault(String thePermission,boolean theDefault){
		defaults.put(thePermission, theDefault);
	}

	private static final String errorNoPermission = "You do not have permission '%s'.";
	private static final String errorNotFromConsole = "You cannot do that from the console.";

	protected boolean checkPermission(CommandSender theCommandSender,
			String thePermissionName,boolean theDefault) {
		boolean theResult = false;
		if(theCommandSender instanceof Player){
			Player thePlayer = (Player)theCommandSender;
			Permission thePermission = getPlugin().getServer().getPluginManager().getPermission(thePermissionName);
			theResult = (thePermission!=null) && thePlayer.hasPermission(thePermission);
			if(!theResult && !shouldSuppressNoPermissionMessages(thePermissionName)){
				getPlugin().sendErrorMessage(theCommandSender, String.format(errorNoPermission,thePermissionName));
			}
		} else {
			theResult = theDefault;
			if(!theResult){
				getPlugin().getLogger().info(errorNotFromConsole);
			}
		}
		return theResult;
	}
	protected abstract boolean shouldSuppressNoPermissionMessages(String thePermissionName);
	public boolean checkPermission(CommandSender theCommandSender,String thePermission){
		boolean theDefault = false;
		if(defaults.containsKey(thePermission)){
			theDefault = defaults.get(thePermission);
		}
		return checkPermission(theCommandSender,thePermission,theDefault);
	}
	
}
